package com.jackrain.nea.utility;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.jackrain.nea.core.db.Tools;
import com.jackrain.nea.exception.NDSException;
import com.jackrain.nea.sys.Command;
import com.jackrain.nea.util.ApplicationContextHandle;
import com.jackrain.nea.util.ReferenceUtil;
import com.jackrain.nea.util.ValueHolder;
import com.jackrain.nea.web.face.User;
import com.jackrain.nea.web.face.impl.UserImpl;
import com.jackrain.nea.web.query.DefaultWebEvent;
import com.jackrain.nea.web.query.QuerySession;
import com.jackrain.nea.web.query.QueryUtils;
import com.jackrain.nea.web.security.Security4Utils;

import javax.servlet.http.HttpServletRequest;
import java.sql.Timestamp;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * @author lzm
 * @date 2017-11-15
 */
public class ServiceUtil {
    private static Pattern pattern = Pattern.compile(".*?([^.]*).api");
    public static <T extends Command>  JSONObject testInvoke(Class<T> apiClazz, HttpServletRequest request, String param){
        String intfName = apiClazz.getName();
        Matcher matcher = pattern.matcher(intfName);
        if(matcher.find()){
            return testInvoke(apiClazz, matcher.group(1), request, param);
        }
        throw new NDSException("尝试从接口名获取groupName失败，请改用指定groupName的重载方法！");
    }

    public static <T extends Command>  JSONObject testInvoke(Class<T> apiClazz, String groupName, HttpServletRequest request, String param){
        return testInvoke(apiClazz, groupName, "1.0", request, param);
    }

    public static <T extends Command> JSONObject testInvoke(Class<T> apiClazz, String groupName, String version, HttpServletRequest request, String param){
        //暂时使用root账号
        User user = Security4Utils.getUser("root");
        return invokeWithUser(apiClazz, user, groupName, version, request, param);
    }

    public static <T extends Command>  JSONObject invoke(Class<T> apiClazz, HttpServletRequest request, String param){
        String intfName = apiClazz.getName();
        Matcher matcher = pattern.matcher(intfName);
        if(matcher.find()){
            return invoke(apiClazz, matcher.group(1), request, param);
        }
        throw new NDSException("尝试从接口名获取groupName失败，请改用指定groupName的重载方法！");
    }

    public static <T extends Command>  JSONObject invoke(Class<T> apiClazz, String groupName, HttpServletRequest request, String param){
        return invoke(apiClazz, groupName, "1.0", request, param);
    }

    public static <T extends Command> JSONObject invoke(Class<T> apiClazz, String groupName, String version, HttpServletRequest request, String param){
        User user = (UserImpl) request.getSession().getAttribute("user");
        return invokeWithUser(apiClazz, user, groupName, version, request, param);
    }

    private static <T extends Command> JSONObject invokeWithUser(Class<T> apiClazz, User user, String groupName, String version, HttpServletRequest request, String param){
        QuerySession querySession = QueryUtils.createQuerySession(user);
        DefaultWebEvent event = new DefaultWebEvent("test", request, false);
        if(param != null) {
            event.put("param", JSON.parseObject(param));
        }
        querySession.setEvent(event);
        Object o = ReferenceUtil.refer(ApplicationContextHandle.getApplicationContext(), apiClazz.getName(), groupName, version);
        ValueHolder result = ((T) o).execute(querySession);
        return result.toJSONObject();
    }

    public static Long fillDefaultValuesBeforeInsert(String tableName, QuerySession session, JSONObject input, Timestamp time){
        Long id = Tools.getSequence(tableName);
        long currentUserId = session.getUser().getId().longValue();

        input.put("ISACTIVE", "Y");
        input.put("AD_CLIENT_ID", Integer.valueOf(session.getUser().getClientId()).longValue());
        input.put("AD_ORG_ID", Integer.valueOf(session.getUser().getOrgId()).longValue());
        input.put("OWNERID", currentUserId);
        input.put("OWNERNAME", session.getUser().getName());
        input.put("OWNERENAME", session.getUser().getEname());
        input.put("MODIFIERID", currentUserId);
        input.put("MODIFIERNAME", session.getUser().getName());
        input.put("MODIFIERENAME", session.getUser().getEname());
        input.put("CREATIONDATE", time);
        input.put("MODIFIEDDATE", time);
        input.put("ID", id);
        return id;
    }

    public static void fillDefaultValuesBeforeUpdate(String tableName, QuerySession session, Long id, JSONObject input, Timestamp time){
        long currentUserId = session.getUser().getId().longValue();
        input.put("ID", id);
        input.put("MODIFIEDDATE",time);
        input.put("MODIFIERID",currentUserId);
        input.put("MODIFIERNAME", session.getUser().getName());
        input.put("MODIFIERENAME", session.getUser().getEname());
    }
}
